package cn.gl.pet.service.impl;

import cn.gl.basic.exception.BusinessException;
import cn.gl.basic.service.impl.BaiduAiAuditServiceImpl;
import cn.gl.basic.util.*;
import cn.gl.order.domain.OrderPetAcquisition;
import cn.gl.order.mapper.OrderPetAcquisitionMapper;
import cn.gl.org.domain.Employee;
import cn.gl.org.domain.Shop;
import cn.gl.org.mapper.EmployeeMapper;
import cn.gl.org.mapper.ShopMapper;
import cn.gl.pet.domain.SearchMasterMsg;
import cn.gl.pet.domain.SearchMasterMsgAuditLog;
import cn.gl.pet.dto.MsgDto;
import cn.gl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.gl.pet.mapper.SearchMasterMsgMapper;
import cn.gl.pet.query.SearchMasterMsgQuery;
import cn.gl.pet.service.ISearchMasterMsgService;
import cn.gl.basic.service.impl.BaseServiceImpl;
import cn.gl.usr.domain.Logininfo;
import cn.gl.usr.domain.User;
import cn.gl.usr.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private BaiduAiAuditServiceImpl baiduAiAuditService;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //添加到数据库
        Logininfo loginInfo = LoginContext.getLoginInfo(request);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.insert(msg);

        //百度ai审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        if(boo1&&boo2){
            //审核通过
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.insert(log);

            //获取离用户最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.laodAll());

            if (nearestShop!=null){//找到最近的店铺
                msg.setShopId(nearestShop.getId());
                //发消息-店铺
                System.out.println("您有新的订单，请尽快处理"+msg.getAddress()+"接回宠物");
            }else{//50公里内没有找到最近的店铺
                msg.setState(3);//放到寻主池-1.没有最近的店铺 2拒单
                //发消息-用户
                System.out.println("你附近暂时没有店铺，请耐心等待！！");
            }
            searchMasterMsgMapper.update(msg);
            return new AjaxResult();
        }else {//审核不通过
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.insert(log);
            //发消息的-用户
            System.out.println("寻主消息发布失败,请修改之后重新发布！！");
            //删除寻主消息
            searchMasterMsgMapper.delete(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息发布失败，请修改之后重新发布！！");

        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo loginInfo = LoginContext.getLoginInfo(request);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询已完成寻主消息
        query.setState(2);
        Logininfo logininfo = LoginContext.getLoginInfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询寻主池寻主消息
        query.setState(3);
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理寻主消息
        query.setState(1);
        Logininfo logininfo = LoginContext.getLoginInfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        //拒单：寻主消息已经分配给某一个店铺，店铺因为某些原因不想接单
        //拒单之后：放入寻主池 - state=3，置空店铺id
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(MsgDto msgDto) {
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());
        if(order!=null && order.getState()==0){//有订单，并且当前订单是待处理 - 处理请求来了
            throw new BusinessException("订单正在处理，请勿重复接单!!!");
        }
        //1.生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.laodOne(msgDto.getMsgId());
        OrderPetAcquisition newOrder = createOrder(msg,msgDto);
        orderPetAcquisitionMapper.insert(newOrder);
        //2.告诉处理人在规定时间内去接回宠物：发短信 2day
        //Employee employee = employeeMapper.loadById(msgDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在2天之内去"+msg.getAddress()+"接回宠物");
        System.out.println("你有新的订单，请在2天之内去"+msg.getAddress()+"接回宠物");
    }
    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        //最后确认时间 - 2天之后的此刻
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //order.setPaytype(); - 没有，接宠物的时候才会有
        //order.setState(); - 实体类默认值待处理0
        //order.setPetId(); - 没有，宠物接后来之后才会有
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

}
